package com.webull.information.center.carwler.job;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.model.CollectRecord;
import com.webull.information.center.carwler.common.model.parm.CollectParm;
import com.webull.information.center.carwler.common.util.eljob.ElasticJobUtil;
import com.webull.information.center.carwler.dao.CollectRecordDao;
import com.webull.information.center.carwler.task.News_CNBC_UsStock_Task;

/**
 * 美股ETF采集cnbc的源
 */
@Component
public class News_CNBC_US_ETF_Job implements SimpleJob {
    protected final Logger logger = LogManager.getLogger(getClass());
    private @Autowired
    News_CNBC_UsStock_Task fullStockFinanceNews;

    private @Autowired
    CollectRecordDao collectRecordDao;
    private final String collectJob = "News_CNBC_etf_Job";
    // private final Integer loop = 50;// 循环20次退出,获取 20*100

    private final static List<Integer> regions0 = Arrays.asList(6);

	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);

		logger.info("News_CNBCETF_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);

		List<Integer> regions = new ArrayList<>(regions0);
		logger.info("News_CNBCETF_Job div size{};exchanges:{};", regions != null ? regions.size() : 0,
				ArrayUtils.toString(regions));
		List<Integer> shardRegions = Optional.ofNullable(ElasticJobUtil.shardingItems(context, regions))
				.orElse(regions);

		process_0(shardRegions);
	}


    public void process_0(List<Integer> regionIds) {
        Collections.shuffle(regionIds);
        logger.info("News_CNBCETF_Job div size{};shardRegions:{};",
                regionIds != null ? regionIds.size() : 0, ArrayUtils.toString(regionIds));
        for (int i = 0; regionIds != null && i < regionIds.size(); i++) {
            try {
                List<CollectRecord> records = collectRecordDao.search(collectParm(regionIds.get(i)));
                Integer lastId = getLastTickeId(records);
                logger.info("News_CNBCETF_Job shardRegions start collectJob{} div ,exchange:{},lastId{}",
                        collectJob, regionIds.get(i), lastId);
                Integer lastId_ = fullStockFinanceNews.etfFinanceNewsExchangeId(regionIds.get(i));
                CollectRecord record = backRecord(regionIds.get(i));
                record.setLastTickerId(lastId_);
                Integer collId = collectRecordDao.add(record);
                logger.info("News_CNBCETF_Job shardRegions end collectJob{} div ,exchange:{},collId{}", collectJob,
                        regionIds.get(i), collId);
            } catch (Exception e) {
                logger.error("News_CNBCETF_Job shardRegions collectJob div error:" + regionIds.get(i), e);
            }
        }
    }

    private Integer getLastTickeId(List<CollectRecord> records) {
        if (records == null || records.isEmpty()) {
            return -1;
        } else {
            return records.get(0).getLastTickerId();
        }
    }

    private CollectParm collectParm(Integer regionId) {
        CollectParm parm = new CollectParm();
        parm.setCollectJob(collectJob);
        parm.setExchangeCode("code");
        parm.setExchangeId(regionId);
        parm.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
        return parm;
    }

    private CollectRecord backRecord(Integer regionId) {
        CollectRecord record = new CollectRecord();
        record.setCollectJob(collectJob);
        record.setExchangeCode("code");
        record.setExchangeId(regionId);
        record.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
        try {
            record.setCustomer(InetAddress.getLocalHost().getHostAddress());
        } catch (Exception e) {
        }
        return record;
    }

}
